import { chatStorage } from './chatStorage';

class WebSocketService {
  constructor() {
    this.ws = null;
    this.messageCallback = null; // 改为单个回调
    this.isConnected = false;
    this.mockMessageTimer = null;
    this.currentChatId = null; // 添加当前聊天ID
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
  }

  connect(userId) {
    if (process.env.NODE_ENV === 'development') {
      console.log('开发环境：模拟 WebSocket 连接');
      this.mockWebSocket(userId);
      return;
    }

    try {
      this.ws = new WebSocket(`ws://your-backend-url/chat?userId=${userId}`);
      this.addWebSocketListeners();
    } catch (error) {
      console.error('WebSocket连接失败:', error);
      this.handleReconnect(userId);
    }
  }

  addWebSocketListeners() {
    this.ws.onopen = () => {
      console.log('WebSocket 连接已建立');
      this.reconnectAttempts = 0; // 重置重连次数
    };

    this.ws.onmessage = (event) => {
      // 将接收到的 JSON 字符串解析为对象
      const message = JSON.parse(event.data);
      // 触发所有注册的回调函数，处理消息
      this.messageCallbacks.forEach(callback => callback(message));
    };

    this.ws.onclose = (event) => {
      console.log('WebSocket连接已关闭, code:', event.code);
      this.handleReconnect();
    };

    this.ws.onerror = (error) => {
      console.error('WebSocket错误:', error);
    };
  }

  handleReconnect(userId) {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
      setTimeout(() => this.connect(userId), delay);
    }
  }

  mockWebSocket(userId) {
    this.isConnected = true;
    console.log(`模拟 WebSocket 已连接，用户ID: ${userId}`);
    this.startMockMessages();
  }

  handleMessage(message) {
    console.log('处理消息:', message);
    if (this.messageCallback) {
      this.messageCallback(message);
    }
  }

  onMessage(callback) {
    this.messageCallback = callback;
  }

  removeMessageListener() {
    this.messageCallback = null;
  }

  startMockMessages() {
    // 清除可能存在的旧定时器
    if (this.mockMessageTimer) {
      clearInterval(this.mockMessageTimer);
    }

    // 创建新的模拟消息定时器
    this.mockMessageTimer = setInterval(() => {
      if (this.isConnected) {
        // 从存储中获取所有会话
        const conversations = chatStorage.getAllConversations();
        if (conversations.length > 0) {
          // 随机选择一个会话
          const randomConv = conversations[Math.floor(Math.random() * conversations.length)];
          
          // 创建模拟消息
          const mockMessage = {
            type: 'chat_message',
            messageId: Date.now(),
            conversationId: randomConv.conversationId,
            senderId: randomConv.user2Id, // 使用对方的ID
            content: `来自用户${randomConv.user2Id}的模拟消息: ${new Date().toLocaleTimeString()}`,
            sentAt: new Date().toISOString()
          };

          // 保存消息并触发回调
          const savedMessage = chatStorage.addMessage(mockMessage);
          this.handleMessage(savedMessage);
        }
      }
    }, 6000); // 每6秒发送一条消息
  }

  send(message) {
    if (process.env.NODE_ENV === 'development') {
      console.log('开发环境：模拟发送消息', message);
      // 修改这里，使用 chatStorage 保存消息后，调用单个回调
      const savedMessage = chatStorage.addMessage(message);
      if (this.messageCallback) {
        this.messageCallback(savedMessage);
      }
      return;
    }
    // ...existing code...
  }

  cleanup() {
    this.isConnected = false;
    if (this.mockMessageTimer) {
      clearInterval(this.mockMessageTimer);
      this.mockMessageTimer = null;
    }
    this.messageCallbacks.clear();
    if (this.ws) {
      this.ws.close();
    }
  }

  // 添加设置当前聊天的方法
  setCurrentChat(chatId) {
    this.currentChatId = chatId;
    console.log('设置当前聊天:', chatId);
  }

  // 移除当前聊天
  removeChat() {
    this.currentChatId = null;
  }
}

export const wsService = new WebSocketService();
